﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// Simple Service Administration Tool for WinNT based systems.
// Copyright © 2010 - Silvan Gehrig
// 
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
// 
// Author:
//  Silvan Gehrig
//
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.ServiceProcess;

using SSATool.DL.Common.Dto;
using ServiceController = System.ServiceProcess.ServiceController;
using ServiceControllerStatus = SSATool.DL.Common.Dto.ServiceControllerStatus;

#endregion

namespace SSATool.DL.ServiceModel
{
    /// <summary>
    /// Provides the functionalities in order to access the service process
    /// data on the current system.
    /// </summary>
    internal class ServiceModelAdapter
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceModelAdapter"/> class.
        /// </summary>
        internal ServiceModelAdapter()
        {
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        internal void SetServiceState(SSATool.DL.Common.Dto.ServiceController service)
        {
            var rawService = (from svc in System.ServiceProcess.ServiceController.GetServices()
                              where svc.ServiceName == service.ServiceName
                              select svc).FirstOrDefault();

             if (rawService != null)
             {
                 switch (service.Status)
                 {
                     case ServiceControllerStatus.Unknown:
                     case ServiceControllerStatus.Stopped:
                     case ServiceControllerStatus.Running:
                     case ServiceControllerStatus.Paused:
                         break; // ignore these states

                     case ServiceControllerStatus.StartPending:
                         StartService(rawService);
                         break;
                     case ServiceControllerStatus.StopPending:
                         StopService(rawService);
                         break;
                     case ServiceControllerStatus.ContinuePending:
                         ContinueService(rawService);
                         break;
                     case ServiceControllerStatus.PausePending:
                         PauseService(rawService);
                         break;
                     
                     default:
                         throw new ArgumentOutOfRangeException();
                 }
             }
        }
    

        internal Dictionary<string, SSATool.DL.Common.Dto.ServiceController> GetServices()
        {
            Dictionary<string, SSATool.DL.Common.Dto.ServiceController> services = new Dictionary<string, Common.Dto.ServiceController>();

            foreach (System.ServiceProcess.ServiceController rawservice in System.ServiceProcess.ServiceController.GetServices())
            {
                services[rawservice.ServiceName] = new Common.Dto.ServiceController
                {
                    CanPauseAndContinue = TryGetServiceValue(svc => svc.CanPauseAndContinue, rawservice),
                    CanShutdown = TryGetServiceValue(svc => svc.CanShutdown, rawservice),
                    CanStop = TryGetServiceValue(svc => svc.CanStop, rawservice),
                    DependentServices = TryGetServiceValue(svc => GetNamesFromServices(svc.DependentServices), rawservice),
                    ServicesDependedOn = TryGetServiceValue(svc => GetNamesFromServices(svc.DependentServices), rawservice),
                    DisplayName = TryGetServiceValue(svc => svc.DisplayName, rawservice),
                    MachineName = TryGetServiceValue(svc => svc.MachineName, rawservice),
                    ServiceName = TryGetServiceValue(svc => svc.ServiceName, rawservice),
                    Status = TryGetServiceValue(svc => GetStatusFromService(svc.Status), rawservice)
                };
            }
            return services;
        }

        private ServiceControllerStatus GetStatusFromService(System.ServiceProcess.ServiceControllerStatus status)
        {
            return (ServiceControllerStatus)Enum.ToObject(typeof (ServiceControllerStatus), status);
        }

        private IList<string> GetNamesFromServices(System.ServiceProcess.ServiceController[] rawServices)
        {
            List<string> names = new List<string>(rawServices.Length);

            foreach (System.ServiceProcess.ServiceController serviceRaw in rawServices)
            {
                names.Add(TryGetServiceValue(svc => svc.ServiceName, serviceRaw));
            }
            return names;
        }

        private T TryGetServiceValue<T>(Func<System.ServiceProcess.ServiceController, T> toExecute, System.ServiceProcess.ServiceController service)
        {
            try
            {
                return toExecute(service);
            }
            catch (InvalidOperationException)
            {
                // ignore this exception. a referenced service may not exist
            }
            catch (Win32Exception)
            {
                // ignore this exception. we may not have the sufficient rights to access each service
            }
            return default(T);
        }

        private void StartService(System.ServiceProcess.ServiceController rawService)
        {
            if (rawService.Status != System.ServiceProcess.ServiceControllerStatus.StartPending
                || rawService.Status != System.ServiceProcess.ServiceControllerStatus.Running)
            {
                rawService.Start();
            }
        }

        private void StopService(System.ServiceProcess.ServiceController rawService)
        {
            if (rawService.CanStop
                && (rawService.Status != System.ServiceProcess.ServiceControllerStatus.StopPending
                || rawService.Status != System.ServiceProcess.ServiceControllerStatus.Stopped))
            {
                rawService.Stop();
            }
        }

        private void ContinueService(System.ServiceProcess.ServiceController rawService)
        {
            if (rawService.CanPauseAndContinue
                && (rawService.Status != System.ServiceProcess.ServiceControllerStatus.ContinuePending
                || rawService.Status != System.ServiceProcess.ServiceControllerStatus.Running))
            {
                rawService.Continue();
            }
        }

        private void PauseService(System.ServiceProcess.ServiceController rawService)
        {
            if (rawService.CanPauseAndContinue
                && (rawService.Status != System.ServiceProcess.ServiceControllerStatus.PausePending
                || rawService.Status != System.ServiceProcess.ServiceControllerStatus.Paused))
            {
                rawService.Continue();
            }
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}
